import 'package:flutter/material.dart';
import 'package:flutter_test_qq/dataBase.dart';
import 'package:flutter_test_qq/mainPage.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'register.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'tencentQQ',
        theme:  ThemeData(
          primarySwatch: Colors.lightGreen,
        ),
        home: Scaffold(
            body: Login()
        ));
  }
}

class Login extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => LoginUI();
}
class LoginUI extends State<Login>{
  Color _themeColor = Colors.lightGreen;
  bool checkBoxSelected = false;
  bool rememberPwd = true;
  bool isShowPwd = false;
  TextEditingController Name = new TextEditingController(); // qq号
  TextEditingController Pwd = new TextEditingController();
  var qqname = '';// qq昵称
  var qqpic = '';


  save() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("QQ",Name.text.toString());
    prefs.setString("Pwd",Pwd.text.toString());
    prefs.setString("Name",qqname);
    prefs.setString("Done",rememberPwd ==true ?"1":"0");
    prefs.setString('Pic', qqpic);
    print('qqpic:${qqpic}');
  }

 get() async{
   SharedPreferences prefs = await SharedPreferences.getInstance();
   var done = prefs.getString("Done").toString();
   if(done == '1'){
     Name.text = prefs.getString("QQ").toString();
     Pwd.text = prefs.getString("Pwd").toString();
   }
   print('done:${done}');
   print('Name.text:${Name.text}');
   print('Pwd.text:${Pwd.text}');
 }
 @override
  void initState() {
    // TODO: implement initState
    // super.initState();
    get();
    print(111);
    // Name.text = '';
    // Pwd.text = '';
  }
  @override
  Widget build(BuildContext context){
    ThemeData themeData = Theme.of(context);
    return Theme(
        data: ThemeData(
            primarySwatch: Colors.lightGreen,
            iconTheme: IconThemeData(color: _themeColor)
        ),
        child:Scaffold(
                resizeToAvoidBottomInset:  false,
                body:SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        SizedBox(
                          child: Row(
                            children: [
                              SizedBox(width: 90,),
                              Image(image: AssetImage("images/qq.png"),width:90.0),
                              Text('QQ',style: TextStyle(fontSize: 50),)
                            ],
                          ),
                          height: 200,
                        ),
                        SizedBox(
                          child: Scrollbar(
                              child: SingleChildScrollView(
                                child:(
                                    TextField(
                                      controller: Name,
                                      keyboardType: TextInputType.number,
                                      decoration: InputDecoration(
                                        filled: true,
                                        contentPadding: EdgeInsets.all(10.0),
                                        enabledBorder: OutlineInputBorder(
                                          borderSide: BorderSide(color: Color(0x00BB0000)),
                                          borderRadius: BorderRadius.all(
                                            Radius.circular(100),
                                          ),
                                        ),
                                        focusColor: Colors.lightGreen,
                                        focusedBorder: OutlineInputBorder(
                                          borderSide: BorderSide(color: Color(0x00000000)),
                                          borderRadius: BorderRadius.all(
                                            Radius.circular(100),
                                          ),
                                        ),
                                        prefixIcon: Icon(Icons.person),
                                        hintText: '请输入QQ号     ',
                                      ),
                                      autofocus: true,
                                      textAlign: TextAlign.right,
                                    )
                                ),
                              )
                          ),
                          height: 70,
                          width: 300,
                        ),
                        SizedBox(
                          child: (
                              TextField(
                                  controller: Pwd,
                                  decoration: InputDecoration(
                                    contentPadding: EdgeInsets.all(10.0),
                                    filled: true,
                                    enabledBorder: OutlineInputBorder(
                                      borderSide: BorderSide(color: Color(0x00BB0000)),
                                      borderRadius: BorderRadius.all(
                                        Radius.circular(100),
                                      ),
                                    ),
                                    focusedBorder: OutlineInputBorder(
                                      borderSide: BorderSide(color: Color(0x00000000)),
                                      borderRadius: BorderRadius.all(
                                        Radius.circular(100),
                                      ),
                                    ),
                                    // labelText: '请输入密码',
                                    hintText: '请输入你的密码',
                                    prefixIcon: Icon(Icons.lock),
                                    suffixIcon: IconButton(
                                        onPressed: () {
                                          setState(() {
                                            isShowPwd = !isShowPwd;
                                          });
                                        },
                                        icon: Icon(
                                            isShowPwd ? Icons.visibility : Icons.visibility_off )),
                                  ),
                                  textAlign: TextAlign.right,
                                  autofocus: true,
                                  obscureText: !isShowPwd
                              )
                          ),
                          height: 50,
                          width: 300,
                        ),
                        // 记住密码单选框
                        Container(
                          child: Row(
                            children: [
                              SizedBox(width: 20,),
                              Checkbox(
                                value: rememberPwd,
                                onChanged: (value){
                                  setState((){rememberPwd = value!;});
                                },
                              ),
                              Text("记住密码"),
                            ],
                          ),
                        ),
                        // 用户协议单选框
                        Container(
                          height: 60,
                          width: 350,
                          child:  Row(
                            children: [
                              SizedBox(width: 15,),
                              Checkbox(
                                value: checkBoxSelected,
                                onChanged: (value){
                                  setState((){checkBoxSelected = value!;});
                                },
                              ),
                              // Text("已阅读并同意服务协议和QQ隐私保护指引"),
                              RichText(text: TextSpan(
                                  text: '已阅读并同意',
                                  style: TextStyle(color: Color(0xFF000000)),
                                  children: <TextSpan>[
                                    TextSpan(
                                      text: '服务协议',
                                      style: TextStyle(color: Colors.lightGreen),
                                    ),
                                    TextSpan(
                                      text:'和',
                                      style: TextStyle(color: Color(0xFF000000)),
                                    ),
                                    TextSpan(
                                      text: 'QQ隐私保护指引',
                                      style: TextStyle(color: Colors.lightGreen),
                                    )
                                  ]
                              ))
                            ],
                          ),
                        ),
                        Container(
                          height: 60,
                          child: MaterialButton(
                            onPressed: (){
                              if (checkBoxSelected) {
                                queryDatabase(context);
                                // Navigator.of(context)
                                //     .push(MaterialPageRoute(builder: (BuildContext context) {
                                //   return mainPage();
                                // }));
                              } else {
                                showDialog<Null>(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (BuildContext context) {
                                      return new AlertDialog(
                                        // title: new Text('标题'),
                                        //可滑动
                                        content: new SingleChildScrollView(
                                          child: new ListBody(
                                            children: <Widget>[
                                              new Text('请勾选用户协议'),
                                            ],
                                          ),
                                        ),
                                        actions: <Widget>[
                                          new ElevatedButton(
                                            child: new Text('确定'),
                                            onPressed: () {
                                              Navigator.of(context).pop();
                                            },
                                          ),
                                        ],
                                      );
                                    });
                                print("请勾选协议");
                              }
                            },
                            // style: ButtonStyle(
                            //     shape: MaterialStateProperty.all(const CircleBorder())
                            // ),
                            child:Text('￫',style: TextStyle(fontSize: 40),),
                            textColor: Colors.white,
                            splashColor:Colors.lightGreen,
                            color: Colors.lightGreen,
                            shape: CircleBorder(side: BorderSide(width: 0,color: Colors.lightGreen)),
                            // child: const Icon(
                            //   Icons.arrow_forward,
                            //   size: 50,
                            // ),
                          ),
                        ),
                        Container(
                            height: 100,
                            width: 300,
                            child:  Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                TextButton(
                                  onPressed: () {  },
                                  child: Text('手机号登录',style: TextStyle(color: Colors.lightGreen),),
                                ),
                                Text('|',style: TextStyle(color: Colors.black),),
                                TextButton(
                                  onPressed:(){
                                    print('进入注册页面');
                                    Navigator.of(context)
                                        .push(MaterialPageRoute(builder: (BuildContext context) {
                                      return registerPage();

                                    }));},
                                  child: Text('新用户注册',style: TextStyle(color: Colors.lightGreen),),
                                ),
                                Text('|',style: TextStyle(color: Colors.black),),
                                TextButton(
                                  onPressed: () {  },
                                  child: Text('更多选项',style: TextStyle(color: Colors.lightGreen),),
                                ),
                              ],
                            )
                        ),
                      ],
                    )
                )
            )
          // body: MyWidget(),
    );

  }
  queryDatabase(BuildContext context) async {
    TableTestProvider testProvider = TableTestProvider();
    //  通过getDatabasePath()方法获取数据库位置
    var databasePath = await getDatabasesPath();
    String path = join(databasePath, 'demo.db');
    // if (databaseFactory.databaseExists(path) == true) {
    //   await testProvider.open(path);
    // } else {
    //   await deleteDatabase(path);
    //
    // }
    // await testProvider.create(path);
    await testProvider.open(path);
    // 查询数据
    Test qq = await testProvider.getTodo(Name.text);

    setState(() {
      qqname = qq.name as String;
      qqpic = qq.pic as String;
    });
    print('qqname保存：${qqname}');
    print('查询:${qq.toMap()}');
    print('qqid:'+Name.text);
    print('qqpwd:'+Pwd.text);

    if(Name.text!=qq.id||Pwd.text!=qq.pwd){
      print('账号或密码不正确');
      Fluttertoast.showToast(msg: '账号或密码不正确',textColor: Colors.white);
    }
    else{
      Fluttertoast.showToast(msg: '登录成功',textColor: Colors.white);
      save();
      if(rememberPwd == false){
        Pwd.text ='';
      }
      Navigator.of(context)
          .push(MaterialPageRoute(builder: (BuildContext context) {
        return mainPage();
      }));
    }
    // 关闭数据库
    testProvider.close();
  }

}


